import request from '@/utils/request'

export const logApi = {
  // 获取日志列表
  async getLogs(params = {}) {
    try {
      // 前端pageIndex从1开始，需要转换为后端的从0开始
      const backendPageIndex = (params.pageIndex || 1) - 1
      
      const requestParams = {
        pageIndex: backendPageIndex,
        pageSize: params.pageSize || 10,
        level: params.level,
        message: params.keyword,
        startDate: params.startDate,
        endDate: params.endDate,
        source: params.source,
        user: params.user
      }
      
      console.log('发送到后端的参数:', JSON.stringify(requestParams, null, 2))
      
      const response = await request.get('/log', { 
        params: requestParams
      })
      
      console.log('日志API响应:', response) // 添加调试日志
      
      // 后端返回的字段名可能是 logs 或 Logs
      if (response.data && (response.data.logs || response.data.Logs)) {
        const logsData = response.data.logs || response.data.Logs;
        const transformedLogs = logsData.map(log => ({
          id: log.id,
          timestamp: log.timestamp,
          level: log.level,
          message: log.message,
          source: log.source,
          userName: log.user,
          stackTrace: log.exception
        }))
        
        return {
          data: {
            items: transformedLogs,
            totalCount: response.data.totalCount || response.data.TotalCount || 0
          }
        }
      }
      
      return { data: { items: [], totalCount: 0 } }
    } catch (error) {
      console.error('获取日志列表失败:', error)
      throw error
    }
  },
  
  // 获取日志详情
  async getLogById(id) {
    try {
      const response = await request.get(`/log/${id}`)
      
      if (response.data) {
        const log = response.data
        return {
          data: {
            id: log.id,
            timestamp: log.timestamp,
            level: log.level,
            message: log.message,
            source: log.source,
            userName: log.user,
            stackTrace: log.exception
          }
        }
      }
      
      throw new Error('日志不存在')
    } catch (error) {
      console.error('获取日志详情失败:', error)
      throw error
    }
  },
  
  // 获取日志统计
  async getLogStats(params = {}) {
    try {
      const response = await request.get('/log/stats', {
        params: {
          level: params.level,
          message: params.keyword,
          startDate: params.startDate,
          endDate: params.endDate,
          source: params.source,
          user: params.user
        }
      })
      
      if (response.data) {
        const stats = response.data
        return {
          data: {
            Error: { count: stats.errorCount || 0 },
            Warning: { count: stats.warningCount || 0 },
            Information: { count: stats.infoCount || 0 },
            Debug: { count: stats.debugCount || 0 }
          }
        }
      }
      
      return { data: { Error: { count: 0 }, Warning: { count: 0 }, Information: { count: 0 }, Debug: { count: 0 } } }
    } catch (error) {
      console.error('获取日志统计失败:', error)
      throw error
    }
  },
  
  // 清理日志
  async clearLogs(params = {}) {
    try {
      const response = await request.post('/log/clear', {
        beforeDate: params.beforeDate,
        level: params.level,
        clearAll: params.clearAll || false
      })
      
      return { 
        message: response.data?.message || response.message || '日志清理成功',
        data: response.data
      }
    } catch (error) {
      console.error('清理日志失败:', error)
      throw error
    }
  },
  
  // 导出日志
  async exportLogs(params = {}) {
    try {
      const response = await request.get('/log/export', {
        params: {
          level: params.level,
          message: params.keyword,
          startDate: params.startDate,
          endDate: params.endDate,
          source: params.source,
          user: params.user
        }
      })
      
      if (response.data) {
        // 生成CSV内容
        const header = 'ID,时间,级别,分类,消息,来源,用户\n'
        let content = header
        
        response.data.forEach(log => {
          const timestamp = new Date(log.timestamp).toLocaleString()
          content += `"${log.id}","${timestamp}","${log.level}","${log.source || '系统'}","${log.message}","${log.source || '数据库服务'}","${log.user || 'system'}"\n`
        })
        
        // 创建Blob对象
        const blob = new Blob([content], { type: 'text/csv;charset=utf-8' })
        return blob
      }
      
      throw new Error('导出数据为空')
    } catch (error) {
      console.error('导出日志失败:', error)
      throw error
    }
  },
  
  // 导出单条日志
  async exportSingleLog(id) {
    try {
      const result = await this.getLogById(id)
      const log = result.data
      
      // 生成CSV内容
      const header = 'ID,时间,级别,分类,消息,来源,用户\n'
      const timestamp = new Date(log.timestamp).toLocaleString()
      const content = header + `"${log.id}","${timestamp}","${log.level}","${log.category}","${log.message}","${log.source}","${log.userName}"\n`
      
      // 创建Blob对象
      const blob = new Blob([content], { type: 'text/csv;charset=utf-8' })
      return blob
    } catch (error) {
      console.error('导出单条日志失败:', error)
      throw error
    }
  }
}

// 日志级别映射
export const LOG_LEVELS = {
  'Error': '错误',
  'Warning': '警告', 
  'Information': '信息',
  'Debug': '调试'
}

// 日志级别颜色映射
export const LOG_LEVEL_COLORS = {
  Error: '#f56c6c',
  Warning: '#e6a23c',
  Info: '#409eff',
  Debug: '#67c23a'
}

// 常见日志事件类型
export const LOG_EVENTS = [
  'UserLogin',
  'UserLogout',
  'DataAccess',
  'SystemError',
  'ApiRequest',
  'FileOperation',
  'ConfigChange',
  'DatabaseOperation',
  'CacheOperation',
  'TaskExecution'
]
